package cn.bat.slsystem.control;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.bat.slsystem.pojo.Msg;
import cn.bat.slsystem.service.MsgServiceImpl;
import cn.bat.slsystem.tools.Constants;

@RequestMapping(value="/msg")
@Controller
public class MsgController {

	@Autowired
	private MsgServiceImpl msgServiceImpl;

	/**
	 * 展示界面
	 * @return
	 */
	@RequestMapping(value="/msglist.html")
	public String msglist(HttpSession session){
		List<String> list = (List) session.getAttribute(Constants.lanjie);
		for (String path : list) {
			if(path.equals("msg/msglist.html")){
				return "msglist";
			}
		}
		return "login";
	}

	/**
	 * 获得数据
	 * @param page
	 * @param limit
	 * @return
	 */
	@RequestMapping(value="/serchlist.html")
	@ResponseBody
	public Object serch(@RequestParam(required=false,defaultValue="1") int page,@RequestParam(required=false,defaultValue="5")int limit){

		PageHelper.startPage(page, limit);
		List<Msg> list =msgServiceImpl.serchlist();
		PageInfo<Msg> pageinfo=new PageInfo<>(list);
		return pageinfo;
	}

	/**
	 * 数据添加界面
	 * @return
	 */
	@RequestMapping(value="/insert.html")
	public String insert(){
		return "insert";
	}


	/**
	 * 数据提交处理器
	 * @param msg
	 * @param msgpath
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/doinsert.html")
	public String doineter(Msg msg,@RequestParam("filemsgpath") MultipartFile filemsgpath,HttpSession session){

		String path=session.getServletContext().getRealPath("upload");
		String weibu=filemsgpath.getOriginalFilename().substring(filemsgpath.getOriginalFilename().indexOf("."));
		String name=UUID.randomUUID().toString()+weibu;

		File file=new File(path, name);
		try {
			filemsgpath.transferTo(file);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		msg.setMsgdownload((long) 0);
		msg.setMsgsize(filemsgpath.getSize()/1048576);
		msg.setCreattime(new Date());
		msg.setMsgpath("/upload/"+name);
		msg.setLastchang(new Date());
		msgServiceImpl.insert(msg);
		return "redirect:/msg/msglist.html";

	}

	@RequestMapping(value="/update.html")
	public String update(int id,HttpSession session){
		Msg msg=msgServiceImpl.serchbyid(id);
		session.setAttribute("updateMsg", msg);
		return "update";
	}

	@RequestMapping(value="/doupdatre.html")
	public String doupdate(Msg msg,@RequestParam("filemsgpath") MultipartFile filemsgpath,HttpSession session){


		String path=session.getServletContext().getRealPath("upload");
		String weibu=filemsgpath.getOriginalFilename().substring(filemsgpath.getOriginalFilename().indexOf("."));
		String name=UUID.randomUUID().toString()+weibu;

		File file=new File(path, name);
		try {
			filemsgpath.transferTo(file);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		msg.setCreattime(new Date());
		msg.setMsgpath("/upload/"+name);
		msg.setLastchang(new Date());
		msg.setMsgsize((filemsgpath.getSize()/1048576));
		System.out.println(msg);
		msgServiceImpl.updateMsg(msg);
		return "redirect:/msg/msglist.html";	
	}

	@RequestMapping(value="/del.html")
	@ResponseBody
	public Object del(int msgid){
		String check="";
		if(msgServiceImpl.delByID(msgid)==1){
			check="ok";
		}else{
			check="no";
		}
		return check;
	}

	@RequestMapping(value="/download.html")
	public String download(int msgid,HttpSession session,HttpServletResponse response){
		Msg msg=msgServiceImpl.serchbyid(msgid);
		System.out.println(msg);
		String path=msg.getMsgpath();
		String destinationfileName=path.substring(8);

		String uploadpath=session.getServletContext().getRealPath("upload");
		//		String destinationfileName=path.substring(8);
		String newpath=uploadpath+"\\"+destinationfileName;
		System.out.println(newpath);
		InputStream fis;

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");

		File file = new File(newpath);
		try {

			if (!file.exists()) {

				System.out.println("=========失败");
			} else {
				// 设置相应头，控制浏览器下载该文件，这里就是会出现当你点击下载后，出现的下载地址框
				response.setHeader("Content-Disposition",
						"attachment;filename=" + path);
				// 读取要下载的文件，保存到文件输入流
				FileInputStream in = new FileInputStream(uploadpath + "\\" + destinationfileName);
				// 创建输出流
				OutputStream out = response.getOutputStream();
				// 创建缓冲区
				byte buffer[] = new byte[1024];
				int len = 0;
				// 循环将输入流中的内容读取到缓冲区中
				while ((len = in.read(buffer)) > 0) {
					// 输出缓冲区内容到浏览器，实现文件下载
					out.write(buffer, 0, len);
				}
				// 关闭文件流
				in.close();
				// 关闭输出流
				out.close();
				Long old=msg.getMsgdownload();
				old=old+1;
				msg.setMsgdownload(old);
				msgServiceImpl.updateMsg(msg);
				return "redirect:/msg/msglist.html";
			}
		} catch (Exception e) {
			// TODO: handle exception

		}
		return null;

	}
	
	@RequestMapping(value="/downcenter.html")
	public String downcenter(){
		return "download";
		
	}
}
